package cn.easyutil.deploy.util;

import ch.ethz.ssh2.*;
import cn.easyutil.deploy.base.SystemType;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 远程连接
 */
public class RemoteUtil {

    private String ip;
    private String username;
    private String password;
    private int port = 22;

    public RemoteUtil(String ip, String username, String password) {
        this.ip = ip;
        this.username = username;
        this.password = password;
    }

    public RemoteUtil(String ip, int port, String username, String password) {
        this.ip = ip;
        this.username = username;
        this.password = password;
        this.port = port;
    }

    /**
     * 获取连接
     * @return
     */
    public Connection connect(){
        Connection conn = new Connection(ip,port);
        try {
            conn.connect();
            boolean auth = conn.authenticateWithPassword(username, password);
            if(!auth){
                throw new RuntimeException("远程机器"+ip+":用户名或密码不正确");
            }
        }catch (Exception e){
            throw new RuntimeException(e);
        }
        return conn;
    }

    /**
     * 将文件拷贝到其他计算机上
     * @param localFile 本地文件地址
     * @param remoteFile 目标机器文件地址
     */
    public void scpPut(File localFile,String remoteFile){
        Connection conn = connect();
        FileInputStream fis = null;
        SCPOutputStream os = null;
        try {
            SCPClient scpClient = new SCPClient(conn);
            os = scpClient.put(localFile.getName(),localFile.length(),remoteFile,null);
            byte[] b = new byte[4096];
            fis = new FileInputStream(localFile);
            int i;
            while ((i = fis.read(b)) != -1) {
                os.write(b, 0, i);
            }
            os.flush();
            os.close();
        }catch (Exception e){
            throw new RuntimeException(e);
        }finally {
            try {
                conn.close();
                if(fis != null){
                    fis.close();
                }
                if(os != null){
                    os.close();
                }
            }catch (Exception e){}

        }
    }

    /**
     * 执行远程命令
     * @param cmd
     */
    public List<String> exec(String cmd){
        Session session = null;
        Connection conn = null;
        BufferedReader br = null;
        List<String> console = new ArrayList<>();
        try {
            conn = connect();
            session =  conn.openSession();
            session.execCommand(cmd);
            //接收目标服务器上的控制台返回结果,输出结果。
            br = new BufferedReader(new InputStreamReader(new StreamGobbler(session.getStdout()),SystemType.current().getCharset()));
            while (true){
                String line = br.readLine();
                if (line == null){
                    break;
                }
                console.add(line);
            }
        }catch (Exception e){
            throw new RuntimeException(e);
        }finally {
            if(conn != null){
                conn.close();
            }
            if(session != null){
                session.close();
            }
            if(br != null){
                try {
                    br.close();
                }catch (Exception e){}
            }
        }
        return console;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }
}
